<template>
  <div class="login-container">
    <div class="login-box">
      <h2>欢迎登录</h2>
      <div v-if="loginStatus === 'loading'" class="loading">
        <p>正在加载二维码...</p>
      </div>
      <div v-else-if="loginStatus === 'error'" class="error">
        <p>{{ errorMessage }}</p>
        <button @click="getQrCode">重试</button>
      </div>
      <div v-else-if="loginStatus === 'scanning'" class="qr-code">
        <img :src="qrCode" alt="微信登录二维码">
        <p>请使用微信扫码登录</p>
      </div>

      <div v-else-if="loginStatus === 'unauthorized'" class="unauthorized">
        <p>抱歉，您暂无访问权限</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Login',
  data() {
    return {
      qrCode: '',
      loginStatus: 'loading',
      errorMessage: ''
    }
  },
  methods: {
    async getQrCode() {
      this.loginStatus = 'loading';
      try {
        const response = await axios.get('http://localhost:8006/api/wx/qrcode');
        this.qrCode = response.data.qrcode;
        this.loginStatus = 'scanning';
      } catch (error) {
        this.loginStatus = 'error';
        this.errorMessage = '获取二维码失败，请重试';
        console.error('获取二维码失败:', error);
      }
    },
    handleMessage(event) {
      const data = event.data;
      if (data.type === 'LOGIN_SUCCESS') {
        localStorage.setItem('token', data.data.token);
        localStorage.setItem('userInfo', JSON.stringify(data.data.user_info));
        
        // 获取重定向地址
        const redirect = this.$route.query.redirect || '/';
        this.$router.push(redirect);
      } else if (data.type === 'LOGIN_UNAUTHORIZED') {
        this.loginStatus = 'unauthorized';
      }
    }
  },
  mounted() {
    this.getQrCode();
    window.addEventListener('message', this.handleMessage);
  },
  beforeUnmount() {
    window.removeEventListener('message', this.handleMessage);
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-box {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.qr-code img {
  width: 200px;
  height: 200px;
  margin: 1rem 0;
}
</style> 